<!--  -->
<template>
  <div class="">
    <el-form>
      <el-tabs tab-position="left" @tab-click="tabClick" style="height:100%">
        <el-tab-pane v-for="(item,index) in responseBody.childList" :label="item.name" :key="index">
          <span :class="item.required?'item_panel':''" slot="label">{{item.name}}</span>
          <!-- tab file为空时不显示 -->
          <el-upload
            v-if="item.files===null&&item.childList===null"
            action=""
            ref="upload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-remove="handleBeforeRemove"
            :multiple="true"
            :http-request="httpUpload"
            class="upload"
            list-type="picture"
            :auto-upload="true"
          >
            <i v-if="allowUpload" class="el-icon-plus"></i>
          </el-upload>
          <!-- tab直接显示图片的回显 -->
          <el-upload
            v-else-if="item.files!=null"
            action=""
            ref="upload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :before-remove="handleBeforeRemove"
            :on-error="handleError"
            :multiple="true"
            :http-request="httpUpload"
            class="upload"
            list-type="picture"
            :auto-upload="true"
            :file-list="item.files"
          >
            <i v-if="allowUpload" class="el-icon-plus"></i>
          </el-upload>
          <!-- 如果文件不是图片类型时的图片回显 -->
          <el-upload
            v-else-if="item.files!=null"
            action=""
            ref="upload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :before-remove="handleBeforeRemove"
            :on-error="handleError"
            :multiple="true"
            :http-request="httpUpload"
            class="upload"
            list-type="picture"
            :auto-upload="true"
            :file-list="item.files"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <!-- collapse时图片操作不一样 -->
          <el-collapse v-model="item.guid" accordion @change="handleChange">
            <el-collapse-item
              v-for="(item1,index) in item.childList"
              :key="index"
              :title="item1.name"
              :name="item1.guid"
            >
              <el-upload
                v-if="item1.files!=null"
                action=""
                :http-request="httpUpload"
                ref="upload"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :before-remove="handleBeforeRemove"
                :on-success="handleSuccess"
                :on-error="handleError"
                :file-list="item1.files"
                :multiple="true"
                class="upload"
                list-type="picture"
                :auto-upload="true"
                :data="uploadselection"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-upload
                v-else
                action=""
                :http-request="httpUpload"
                ref="upload"
                :before-remove="handleBeforeRemove"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :on-error="handleError"
                :multiple="true"
                class="upload"
                list-type="picture"
                :auto-upload="true"
                :data="uploadselection"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <el-dialog :title="imgTitle" :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
      <footer>
        <el-button type="primary" @click="handleDownload">文件下载</el-button>
      </footer>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {
  getFileMenu,
  insertFileMenu,
  delFile,
  download,
  test,
  upload,
  fileUpload
} from "@/api/upload";
import img from "@/assets/404_images/1.png";
import { mapGetters } from "vuex";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      imgTitle: "图片的标题",
      uploadselection: {
        roomGuids: [],
        menuGuid: ""
      },
      responseBody: {},
      fileList: [{ name: "test", url: img }],
      uploadRequired: []
    };
  },
  //监听属性 类似于data概念
  computed: {
    ...mapGetters(["upload"])
  },
  //监控data中的数据变化
  watch: {
    selectionGuid(val) {
      console.log("selectionGuid", val);
      this.fetchData();
    },
    selectMenu(val) {
      console.log("selectMenu", val);
      this.responseBody = val;
      this.imgRequire();
    },
    rootGuid(val) {
      console.log("rootGuid", val);
      this.fetchData();
      this.rootGuid = val;
    }
  },
  //方法集合
  methods: {
    imgRequire() {
      this.uploadRequired = this.uploadRequired.filter(
        item => item.guid != this.uploadselection.menuGuid
      );
      this.$emit("required", this.uploadRequired);
      console.log("filter", this.uploadRequired);
    },
    httpUpload(file) {
      console.log("menuGuid", this.uploadselection.menuGuid);
      this.imgRequire();
      const formData = new FormData();
      formData.append("file", file.file);
      formData.append("roomGuids", this.uploadselection.roomGuids);
      formData.append("menuGuid", this.uploadselection.menuGuid);
      if (this.upload === 1) {
        fileUpload(formData).then(res => {
          if (res.code === 100) {
            this.$message({ message: "上传成功!", type: "success" });
            this.$emit("uploadBody", res.body);
          }
        });
      } else {
        upload(formData).then(res => {
          if (res.code === 100) {
            this.$message({ message: "上传成功!", type: "success" });
          }
        });
      }
    },
    tabClick(tab, event) {
      console.log("tab", tab);
      console.log("event", event);
      console.log("responseobdy", this.responseBody);
      this.responseBody.childList.forEach(item => {
        console.log("item", item);
        if (item.name === tab.label) {
          this.uploadselection.menuGuid = item.guid;
        }
      });
    },
    fetchData() {
      let data = {
        roomGuids: this.selectionGuid,
        guid: this.rootGuid
      };
      getFileMenu(data)
        .then(response => {
          this.responseBody = response.body;
          this.uploadselection.menuGuid = response.body.childList[0].guid; //默认为打开的第一个guid
        })
        .catch(error => {
          console.log(error);
        });
    },
    //文件删除前的钩子
    handleBeforeRemove(file, fileList) {
      let url = { url: file.url };
      this.$confirm("此操作将永久删除该文件或图片, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delFile(url).then(response => {
            if (response.code === 100) {
              this.$message({ message: "删除成功!", type: "success" });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
      return false;
    },
    //文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log(file.url);
    },
    //点击图片预览大图
    handlePictureCardPreview(file) {
      console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      this.imgTitle = file.name;
    },
    handleChange(val) {
      this.uploadselection.menuGuid = val;
    },
    //上传前文件类型钩子
    beforeAvatarUpload(file) {
      console.log(file.type + "大小:" + file.size);
      const isJPG = file.type === "image/jpeg";
      const isWORD = file.type === "application/msword";
      const isEXCEL = file.type === "application/vnd.ms-excel";
      const png = file.type === "image/png";
    },
    //文件上传成功时的钩子
    handleSuccess(response, file, fileList) {
      if (response.code === 100) {
        this.$message({
          message: "上传文件成功!",
          type: "success"
        });
        this.fetchData();
      }
      console.log(response);
      console.log(file);
      console.log(fileList);
    },
    //文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message({
        message: "上传文件失败!",
        type: "error"
      });
    },
    //文件下载
    handleDownload() {
      var btn = document.createElement("a");
      btn.setAttribute("download", ""); // download属性
      btn.setAttribute("href", this.dialogImageUrl); // href链接
      btn.click(); // 自执行点击事件
    }
  },
  props: {
    //选择资产的guid
    selectionGuid: {
      type: Array,
      defualt: []
    },
    //出入账传的下拉菜单项
    selectMenu: {
      type: Object,
      default: null
    },
    //根guid
    rootGuid: {
      type: String,
      defualt: ""
    },
    allowUpload: {
      type: Boolean,
      default: true
    }
  },
  beforeCreate() {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    //出入账时
    if (this.selectMenu != null) {
      this.responseBody = this.selectMenu;
      this.uploadselection.roomGuids = this.selectionGuid;
      //默认选中第一个menuguid
      this.uploadselection.menuGuid = this.selectMenu.childList[0].guid;
      this.selectMenu.childList.forEach(item => {
        console.log("item", item.required);
        if (item.required && item.files === null) {
          this.uploadRequired.push(item);
          this.$emit("required", this.uploadRequired);
        }
      });
    } else {
      this.uploadselection.guid = "a46015f715a94b7ea3668e6e89b23b16";
      this.fetchData();
    }
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.item_panel:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.upload {
  margin: 10px;
}
</style>